<template>
  <div class="asset-manage-container">
    <div class="header-container">
      <span class="page-title">资产管理</span>
    </div>

    <!-- 搜索区域 -->
    <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="资产名称">
        <el-input v-model="queryParams.assetName" placeholder="请输入资产名称"></el-input>
      </el-form-item>
      <el-form-item label="资产类型">
        <el-select v-model="queryParams.categoryName"
                   placeholder="请选择资产类型"
                   style="width: 150px;"
                   clearable
        >
          <el-option label="设备" value="1"></el-option>
          <el-option label="耗材" value="2"></el-option>
          <el-option label="工具" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资产状态">
        <el-select
            v-model="queryParams.statusName"
            placeholder="请选择状态"
            clearable
            style="width: 150px;"
        >
          <el-option label="在库" value="1"/>
          <el-option label="借出" value="2"/>
          <el-option label="维修" value="3"/>
          <el-option label="出库" value="4"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
        <el-button @click="handleReset" :icon="Refresh">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="openAddDialog">新增资产</el-button>
      <el-upload
          class="upload-demo"
          accept=".xls,.xlsx"
          :show-file-list="false"
          :on-change="handleFileUpload"
          :auto-upload="false">
        <template #trigger>
          <el-button type="success" :icon="UploadFilled">导入资产</el-button>
        </template>
      </el-upload>
      <el-button type="danger" @click="handleExport" :icon="Download">导出资产</el-button>
    </div>

    <!-- 表格 -->
    <el-table v-loading="assetManage.loading" :data="assetList" style="width: 100%" border stripe class="asset-table">
      <el-table-column prop="assetId" label="资产ID" width="80" align="center"></el-table-column>
      <el-table-column prop="assetName" label="资产名称" align="center"></el-table-column>
      <el-table-column prop="assetType" label="资产型号" align="center"></el-table-column>
      <el-table-column prop="statusName" label="状态" align="center"></el-table-column>
      <el-table-column prop="categoryName" label="资产分类" align="center"></el-table-column>
      <el-table-column prop="purchaseDate" label="购买日期" align="center"></el-table-column>
      <el-table-column prop="purchasePrice" label="购买价格" align="center"></el-table-column>
      <el-table-column prop="stockQuantity" label="库存量"></el-table-column>
      <el-table-column prop="location" label="存放地点"></el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <el-button size="small" type="primary" link @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination" style="margin-top: 20px; display: flex; justify-content: center;">
      <el-pagination
          :current-page="queryParams.page"
          :page-size="queryParams.pageSize"
          :total="assetManage.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :model-value="dialogVisible" width="40%" @close="closeDialog">
      <el-form ref="assetFormRef" :model="assetForm" :rules="rules" label-width="100px">
        <el-form-item label="资产名称" prop="assetName">
          <el-input v-model="assetForm.assetName"></el-input>
        </el-form-item>
        <el-form-item label="资产型号" prop="assetType">
          <el-input v-model="assetForm.assetType"></el-input>
        </el-form-item>
        <el-form-item label="资产分类" prop="categoryName">
          <el-select v-model="assetForm.categoryName" placeholder="请选择资产类型">
            <el-option label="设备" value="1"></el-option>
            <el-option label="耗材" value="2"></el-option>
            <el-option label="工具" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="购买日期" prop="purchaseDate">
          <el-date-picker v-model="assetForm.purchaseDate" type="date" placeholder="选择日期"
                          value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item label="购买价格" prop="purchasePrice">
          <el-input v-model.number="assetForm.purchasePrice" type="number"></el-input>
        </el-form-item>
        <el-form-item label="库存量" prop="stockQuantity">
          <el-input v-model.number="assetForm.stockQuantity" type="number"></el-input>
        </el-form-item>
        <el-form-item label="存放地点" prop="location">
          <el-input v-model="assetForm.location"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {nextTick, onMounted, reactive, ref, watch} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {adminAssetManage} from '@/stores/admin/AssetManage.js'
import {storeToRefs} from "pinia";
import dayjs from 'dayjs';
import * as XLSX from 'xlsx';
import {Search, Refresh, UploadFilled, Download} from '@element-plus/icons-vue'; // 引入图标

const assetManage = adminAssetManage();
const {assetList, total, queryParams, loading} = storeToRefs(assetManage);

const dialogVisible = ref(false);
const dialogTitle = ref('');
const assetFormRef = ref(null);

const assetForm = reactive({
  assetId: null,
  assetName: '',
  assetType: '',
  categoryName: '',
  statusName: '在库',
  purchaseDate: '',
  purchasePrice: 0,
  stockQuantity: 0,
  location: '',
});

const rules = reactive({
  assetName: [
    {required: true, message: '资产名称不能为空', trigger: 'blur'},
    {max: 50, message: '资产名称长度不能超过 50 个字符', trigger: 'blur'}
  ],
  assetType: [
    {required: true, message: '资产型号不能为空', trigger: 'blur'},
    {max: 50, message: '资产型号长度不能超过 50 个字符', trigger: 'blur'}
  ],
  categoryName: [{required: true, message: '资产分类不能为空', trigger: 'change'}],
  purchaseDate: [{required: true, message: '购买日期不能为空', trigger: 'change'}],
  purchasePrice: [
    {required: true, message: '购买价格不能为空', trigger: 'blur', type: 'number'},
    {min: 0, message: '购买价格不能为负数', trigger: 'blur', type: 'number'}
  ],
  stockQuantity: [
    {required: true, message: '库存量不能为空', trigger: 'blur', type: 'number'},
    {min: 0, message: '库存量不能为负数', trigger: 'blur', type: 'number'}
  ],
  location: [
    {required: true, message: '存放地点不能为空', trigger: 'blur'},
    {max: 50, message: '存放地点长度不能超过 50 个字符', trigger: 'blur'}
  ],
});


// watch(queryParams, () => {
//   assetManage.getAssets();
// }, {deep: true});


// 搜索
const handleSearch = () => {
  assetManage.setPage(1);
  assetManage.getAssets();
};

// 重置
const handleReset = () => {
  assetManage.resetQuery();
  assetManage.getAssets();
};

// 导入
const handleFileUpload = async (file) => {
  const rawFile = file.raw;
  if (!rawFile) return;

  const reader = new FileReader();
  reader.onload = async (e) => {
    const binaryString = e.target.result;
    const workbook = XLSX.read(binaryString, {type: 'binary'});
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet);

    // 格式化日期，假设Excel日期列的key是 'purchaseDate'
    const formattedJsonData = jsonData.map(item => {
      if (item.purchaseDate) {
        if (typeof item.purchaseDate === 'number') { // 尝试处理数字日期 (Excel 序列号)
          const excelEpoch = new Date(Date.UTC(1899, 11, 30)); // Excel 的 epoch date
          const javaScriptDate = new Date(excelEpoch.getTime() + (item.purchaseDate - 1) * 24 * 3600 * 1000); // 减 1 因为 Excel 认为 1900/1/1 是第一天
          item.purchaseDate = dayjs(javaScriptDate).format('YYYY-MM-DD'); // 格式化为 YYYY-MM-DD
        } else {
          item.purchaseDate = dayjs(item.purchaseDate).format('YYYY-MM-DD'); // 假设已经是日期字符串，直接格式化
        }
      }
      return item;
    });


    try {
      const success = await assetManage.uploadAsset(formattedJsonData);
      if (success) {
        assetManage.getAssets(); // 刷新列表
      }
    } catch (error) {
      console.error("导入失败", error);
      ElMessage.error('导入资产失败');
    }
  };
  reader.onerror = () => {
    ElMessage.error('文件读取失败');
  };
  reader.readAsBinaryString(rawFile);
};


// 导出
const handleExport = async () => {
  try {
    await assetManage.downloadAsset(queryParams); // 传递当前查询参数
    ElMessage.success('导出资产成功'); // 导出成功仅提示，具体下载由后端处理
  } catch (error) {
    console.error("导出失败", error);
    ElMessage.error('导出资产失败');
  }
};


// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定删除该资产吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        assetManage.getAssets(); // 刷新列表
        assetManage.removeAsset(row.assetId).then(
        )
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
};

// 打开新增/编辑对话框
const openAddDialog = () => {
  dialogTitle.value = '新增资产';
  Object.assign(assetForm, {
    assetId: null,
    assetName: '',
    assetType: '',
    categoryName: '',
    statusName: '在库',
    purchaseDate: '',
    purchasePrice: null,
    stockQuantity: null,
    location: '',
  });
  dialogVisible.value = true;
  nextTick(() => { // 确保 dialogVisible 更新后执行 resetFields
    assetFormRef.value?.resetFields();
  });
};

const openEditDialog = async (row) => {
  dialogTitle.value = '编辑资产';
  await assetManage.fetchAssetDetail(row.assetId);
  if (assetManage.assetDetail) { // 确保获取到详情数据
    // 使用 assetDetail 填充表单
    Object.assign(assetForm, {...assetManage.assetDetail});
    dialogVisible.value = true;
    nextTick(() => {
      assetFormRef.value?.resetFields();
    });
  } else {
    ElMessage.error('获取资产详情失败，请重试');
  }
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
  assetFormRef.value?.resetFields(); // 关闭时也重置表单，避免上次校验错误残留
};

// 保存
const handleSave = async () => {
  assetFormRef.value?.validate(async (valid) => {
    if (valid) {
      let success = false;
      const params = {...assetForm};
      params.purchaseDate = dayjs(params.purchaseDate).format('YYYY-MM-DD'); // 确保日期格式正确

      if (assetForm.assetId) {
        // 编辑
        success = await assetManage.modifyAsset(assetForm.assetId, params);
      } else {
        // 新增
        success = await assetManage.createAsset(params);
      }

      if (success) {
        closeDialog();
        assetManage.getAssets(); // 刷新列表
      }
    } else {
      ElMessage.error('请填写正确的表单信息');
    }
  });
};

// 分页
const handleSizeChange = (val) => {
  assetManage.setPageSize(val);
  assetManage.getAssets();
};

const handleCurrentChange = (val) => {
  assetManage.setPage(val);
  assetManage.getAssets();
};
// 初始化
onMounted(() => {
  assetManage.getAssets();
});
</script>

<style>
.asset-manage-container {
  padding: 20px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.search-form {
  margin-bottom: 15px;
  background-color: #fff;
  padding: 20px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.operation-buttons {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.operation-buttons .el-button {
  border-radius: 4px;
}

/* 表格样式 */
.asset-table {
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.el-table {
  --el-table-row-hover-bg-color: #ecf5ff;
  --el-table-header-bg-color: #e8f0fe;
  --el-table-header-text-color: #333;
}

/* 操作列按钮样式 */
.el-table .el-button--text {
  margin-right: 8px;
}

/* 分页样式 */
.pagination {
  margin-top: 20px;

}

/* 对话框样式 */
.el-dialog__header {
  background-color: #f0f2f5;
  padding: 15px 20px;
  border-bottom: 1px solid #e6e6e6;
}

.el-dialog__title {
  font-size: 18px;
  color: #333;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog-footer {
  padding: 15px 20px;
  border-top: 1px solid #e6e6e6;
  text-align: right;
  background-color: #f0f2f5;
  border-bottom-left-radius: 6px;
  border-bottom-right-radius: 6px;
}

.el-dialog-footer .el-button + .el-button {
  margin-left: 10px;
}
</style>